package com.ygswglxt.leave.controller;

import com.ygswglxt.leave.entity.LeaveRecord;
import com.ygswglxt.leave.service.LeaveService;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/leave")
public class LeaveController {
    
    @Autowired
    private LeaveService leaveService;
    
    @PostMapping("/apply")
    public Result<String> applyLeave(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long userId = Long.parseLong(request.getHeader("userId"));
            LeaveRecord leaveRecord = new LeaveRecord();
            leaveRecord.setUserId(userId);
            leaveRecord.setType((String) params.get("type"));
            
            // 处理日期字符串
            String startDateStr = (String) params.get("startDate");
            String endDateStr = (String) params.get("endDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            
            if (startDateStr != null && !startDateStr.isEmpty()) {
                leaveRecord.setStartDate(sdf.parse(startDateStr));
            }
            if (endDateStr != null && !endDateStr.isEmpty()) {
                leaveRecord.setEndDate(sdf.parse(endDateStr));
            }
            
            if (params.get("days") != null) {
                leaveRecord.setDays(Integer.parseInt(params.get("days").toString()));
            }
            leaveRecord.setReason((String) params.get("reason"));
            
            return leaveService.applyLeave(leaveRecord);
        } catch (Exception e) {
            return Result.error("申请失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/approve")
    public Result<String> approveLeave(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Long leaveId = Long.parseLong(params.get("leaveId").toString());
        Long approverId = Long.parseLong(request.getHeader("userId"));
        String status = params.get("status").toString();
        return leaveService.approveLeave(leaveId, approverId, status);
    }
    
    @GetMapping("/my")
    public Result<List<LeaveRecord>> getMyLeaves(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return leaveService.getMyLeaves(userId);
    }
    
    @GetMapping("/pending")
    public Result<List<LeaveRecord>> getPendingLeaves(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role) && !"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return leaveService.getPendingLeaves();
    }
    
    // 假期统计（HR使用）
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getLeaveStatistics(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (role == null || !"HR".equals(role)) {
            return Result.error(403, "无权限访问，仅HR角色可以查看假期统计");
        }
        try {
            return leaveService.getLeaveStatistics();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }
    
    // 导出请假记录
    @GetMapping("/export")
    public void exportLeaveRecords(
            @RequestParam(required = false) String status,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String userIdStr = request.getHeader("userId");
            String role = request.getHeader("role");
            Long userId = null;
            
            // 只有员工查看自己的记录，HR和经理可以查看所有
            if (!"HR".equals(role) && !"MANAGER".equals(role)) {
                userId = Long.parseLong(userIdStr);
            }
            
            leaveService.exportLeaveRecords(response, userId, status);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
}

